﻿using System;
using System.Data;
using System.Configuration;
using System.Net.Mail;
using System.Net.Configuration;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;


public class Sendmail
{
    public delegate void CommandActionHandle(object sender, AsyncCompletedEventArgs e);
    //public event CommandActionHandle OnCommandAction;
    public Sendmail(string username, string password, string server, string protocol, int port)
    {
        _UserName = username;
        _Password = password;
        _Host = server;// String.Format("{0}.{1}", protocol, server);
        _Port = port;
        _Domain = server;
    }
    static string _FromAddress = "";
    static string _FromName = "";
    static string _Host = "smtp.gmail.com";// "smtp.gmail.com";
    static int _Port = 587; ////25465;
    static string _UserName = "";
    static string _Password = "";
    static string _Domain = "mail.google.com";
    public static string _defaultAddress = "support-inventory@hlhvjoc.com.vn";
    public static string _defaultName = "Inventory System Mail Support";
    public static string FromName
    {
        get { return Sendmail._FromName; }
        set { Sendmail._FromName = value; }
    }
    public static String FormAddress
    {
        get
        {
            //SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
            return _UserName;
        }
        set
        {
            _FromAddress = value;
        }
    }

    public void Cancel()
    {
        if (client != null) client.SendAsyncCancel();
        if (message != null) message.Dispose();
    }

    MailMessage message;
    SmtpClient client;
    public string SendMail(string subject, string body, Dictionary<string, string> emails, string attFiles, bool isHtml, bool isSSL, SendCompletedEventHandler sendMailEvent = null)
    {
        string sErr = "";
        try
        {
            if (emails.Count == 0)
            {
                return "DON'T HAVE any mail to send!";
            }


            MailAddress from;

            if (_FromAddress != "") from = new MailAddress(_FromAddress, _FromName, System.Text.Encoding.UTF8);
            else from = new MailAddress(_defaultAddress, _defaultName, System.Text.Encoding.UTF8);

            message = new MailMessage();

            message.From = from;
            foreach (KeyValuePair<string, string> it in emails)
            {
                MailAddress tomail = new MailAddress(it.Key, it.Value);

                message.To.Add(tomail);
            }

            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = isHtml;

            string[] arrAtt = attFiles.Split(';');
            for (int i = 0; i < arrAtt.Length; i++)
            {
                if (File.Exists(arrAtt[i]))
                {
                    Attachment itemAtt = new Attachment(arrAtt[i]);
                    message.Attachments.Add(itemAtt);
                }
            }

            client = new SmtpClient(_Host);

            if (sendMailEvent != null) client.SendCompleted += sendMailEvent;

            if (_Password != "")
                client.Credentials = new NetworkCredential(_UserName, _Password);
            else
                client.UseDefaultCredentials = true;

            if (_Port != 0) client.Port = _Port;

            if (_Password != "") client.EnableSsl = isSSL;
            else client.EnableSsl = false;

            string userState = "Begin sending mail";
            if (LogMsg != null) userState = LogMsg;

            if (sendMailEvent != null) client.SendAsync(message, userState);
            else
            {
                client.Send(message);
                message.Dispose();
            }

        }
        catch (SmtpException ex)
        {
            sErr += ex.Message + "\n" + ex.InnerException.Message + "[Stack]:" + ex.StackTrace + "\n" + ex.InnerException.StackTrace;// 
        }
        return sErr;
    }

    public string SendMail(string subject, string body, string toMail, string toName, string attFiles, bool isHtml, bool isSSL, SendCompletedEventHandler sendMailEvent = null)
    {
        Dictionary<string, string> emails = new Dictionary<string, string>();
        emails.Add(toMail, toName);
        return SendMail(subject, body, emails, attFiles, isHtml, isSSL, sendMailEvent);

    }

    public string LogMsg { get; set; }
}
